// 加载 iconify 图标
import { downloadAndInstall } from '@/iconify'

import icons from '@/iconify/index.json'
// 自定义指令
import directive from '@/utils/directive'

import App from './App.vue'

import router from './router'
import pinia from './store'
import uiProvider from './ui/provider'

// import Cookies from 'js-cookie'

import { download } from '@/utils/request'
import { parseTime, resetForm, addDateRange, handleTree, selectDictLabel, selectDictLabels } from '@/utils/common'
import { func } from '@/utils/func'

import plugins from '@/plugins/index' // plugins

// svg图标
import SvgIcon from '@/components/SvgIcon/index.vue'
import elementIcons from '@/components/SvgIcon/svgicon'

import '@/utils/systemCopyright'

// 加载 svg 图标
import 'virtual:svg-icons-register'
import 'virtual:uno.css'
import '@unocss/reset/tailwind-compat.css'
// 全局样式
import '@/assets/styles/globals.css'
import '@/assets/styles/common.css'

import { installDict } from '@/components/Dict'

const app = createApp(App)

// 全局方法挂载
app.config.globalProperties.download = download
app.config.globalProperties.parseTime = parseTime
app.config.globalProperties.resetForm = resetForm
app.config.globalProperties.handleTree = handleTree
app.config.globalProperties.addDateRange = addDateRange
app.config.globalProperties.selectDictLabel = selectDictLabel
app.config.globalProperties.selectDictLabels = selectDictLabels
app.config.globalProperties.func = func

// 全局组件挂载 - 延迟加载非关键组件
// BigFileUpload 和 QuillEditor 改为异步加载，首次访问时不阻塞
Promise.all([
  import('@/components/BigFileUpload/index.vue').then(m => m.default),
  import('@/components/QuillEditor/index.vue').then(m => m.default),
]).then(([BigFileUpload, QuillEditor]) => {
  app.component('BigFileUpload', BigFileUpload)
  app.component('QuillEditor', QuillEditor)
}).catch(() => {
  // 静默处理加载错误
})


installDict(app)

app.use(pinia)
app.use(router)
app.use(plugins)
app.use(elementIcons)
app.use(uiProvider)
app.component('svg-icon', SvgIcon)
directive(app)

// 异步加载图标，避免阻塞应用启动
if (icons.isOfflineUse) {
  // 使用 requestIdleCallback 或 setTimeout 延迟加载图标
  const loadIcons = () => {
    for (const info of icons.collections) {
      downloadAndInstall(info).catch(() => {
        // 静默处理加载错误，避免影响应用启动
      })
    }
  }
  
  // 优先使用 requestIdleCallback，浏览器空闲时加载
  if ('requestIdleCallback' in window) {
    requestIdleCallback(loadIcons, { timeout: 2000 })
  } else {
    // 降级方案：延迟 100ms 后加载
    setTimeout(loadIcons, 100)
  }
}

app.mount('#app')
